﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.core.database;
using com.core.controls;
using System.Web.UI;


namespace com.core.module.controls
{
    public class InputControl : System.Web.UI.WebControls.CompositeControl
    {
        
        public bool ReadOnly { get; set; }
        public string TypeName { get; set; }
        public object ItemId { get { return ViewState["ItemId"] == null ? null : ViewState["ItemId"]; } set { ViewState["ItemId"] = value; EnsureChildControls(); } }
        private Control FindControl(string id)
        {
            foreach(Control control in Controls)
            {
                if(control.ID == id)
                {
                    return control;
                }
            }
            return null;
        }
        public bool Save()
        {
            
            GenericBusiness.ItemType itemType = null;
            GenericBusiness bu = new GenericBusiness();
            DataItem data = new DataItem();
            itemType = GenericBusiness.ItemType.LoadType(TypeName);
            foreach (GenericBusiness.ItemTypeSchema schema in itemType.Schemas)
            {
                Control control = FindControl(schema.InputControl + schema.Column);

                switch(schema.InputControl)
                {
                    case GenericBusiness.ControlType.CheckBox:
                        data[schema.Column] = ((CheckBox)control).Checked? "1" : "0";
                        break;
                    case GenericBusiness.ControlType.DropdownList:
                        data[schema.Column] = ((DropDownList)control).SelectedValue;
                        break;
                    case GenericBusiness.ControlType.ListBox:
                        data[schema.Column] = ((ListBox)control).SelectedValue;
                        break;
                    case GenericBusiness.ControlType.RadioButtonList:
                        data[schema.Column] = ((RadioButtonList)control).SelectedValue;
                        break;
                    case GenericBusiness.ControlType.TextArea:
                        data[schema.Column] = ((TextBox)control).Text;
                        break;
                    case GenericBusiness.ControlType.TextBox:
                        data[schema.Column] = ((TextBox)control).Text;
                        break;
                    default:
                        break;

                }
            }
            if (ItemId == null)
            {
                return bu.InsertItem(itemType, data);
            }
            else
            {
                data[itemType.KeyField] = ItemId;
                return bu.UpdateItem(itemType, data);
            }
        }
        void CreateChildControlsForReadOnlyMode()
        {
            Controls.Clear();
            DataItem itemDetail = null;
            GenericBusiness.ItemType itemType = null;
            GenericBusiness bu = new GenericBusiness();
            itemType = GenericBusiness.ItemType.LoadType(TypeName);
            if (ItemId != null)
            {
                //load data detail here
                itemDetail = bu.GetItem(itemType, ItemId);
                if (itemDetail != null)
                {
                    foreach (GenericBusiness.ItemTypeSchema schema in itemType.Schemas)
                    {
                        Controls.Add(new Label() { ID = "Label" + schema.Column, Text = schema.Display });
                        Literal litValue = new Literal() { ID = "Literal" + schema.Column };
                        switch (schema.InputControl)
                        {
                            case GenericBusiness.ControlType.DropdownList:
                            case GenericBusiness.ControlType.ListBox:
                            case GenericBusiness.ControlType.RadioButtonList:
                                if (schema.Data.StartsWith("ref:"))
                                {
                                    string refItemName = schema.Data.Replace("ref:", string.Empty);
                                    GenericBusiness.ItemType refItemType = GenericBusiness.ItemType.LoadType(refItemName);
                                    if (refItemType != null)
                                    {
                                        int count = 0;
                                        DataItem[] refItemList = bu.GetItems(refItemType, null, null, 0, 0, ref count);
                                        for (int i = 0; i < count; i++)
                                        {
                                            if (refItemList[i][refItemType.KeyField].ToString() == itemDetail[schema.Column].ToString())
                                            {
                                                litValue.Text = refItemList[i][refItemType.DisplayField].ToString();
                                                break;
                                            }
                                        }
                                    }
                                }
                                else if (schema.Data.StartsWith("item:"))
                                {
                                    string refString = schema.Data.Replace("item:", string.Empty);
                                    string[] refItemStrings = refString.Split('|');
                                    foreach (string refItemString in refItemStrings)
                                    {
                                        //refItemString = "1:Girl"
                                        string[] refItem = refItemString.Split(':');
                                        if (refItem[0] == itemDetail[schema.Column].ToString())
                                        {
                                            litValue.Text = refItem[1];
                                            break;
                                        }
                                    }
                                }
                                break;
                            default:
                                litValue.Text = itemDetail[schema.Column].ToString();
                                break;
                        }
                        Controls.Add(litValue);
                    }
                }
            }
        }
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            if (ReadOnly)
            {
                CreateChildControlsForReadOnlyMode();
                return;
            }
            Controls.Clear();
            DataItem itemDetail = null;
            GenericBusiness.ItemType itemType = null;
            GenericBusiness bu = new GenericBusiness();
            itemType = GenericBusiness.ItemType.LoadType(TypeName);
            if (ItemId != null)
            {
                //load data detail here
                itemDetail = bu.GetItem(itemType, ItemId);
            }
            //more code here
            //.......
            foreach (GenericBusiness.ItemTypeSchema schema in itemType.Schemas)
            {
                if (schema.InputControl != GenericBusiness.ControlType.None)
                {
                    Controls.Add(new Label() { ID = "Label" + schema.Column, Text = schema.Display });
                }
                switch(schema.InputControl)
                {
                    case GenericBusiness.ControlType.CheckBox:
                        Controls.Add(new CheckBox() { 
                            ID = schema.InputControl + schema.Column, 
                            Checked = itemDetail != null ? (bool)itemDetail[schema.Column] : false });
                        break;
                    case GenericBusiness.ControlType.DropdownList:
                        DropDownList dropdown = new DropDownList()
                        {
                            ID = schema.InputControl + schema.Column,                         
                        };
                        if (schema.Data.StartsWith("ref:"))
                        {
                            string refItemName = schema.Data.Replace("ref:", string.Empty);
                            GenericBusiness.ItemType refItemType = GenericBusiness.ItemType.LoadType(refItemName);
                            if (refItemType != null)
                            {
                                dropdown.DataValueField = refItemType.KeyField;
                                dropdown.DataTextField = refItemType.DisplayField;
                                int count = 0;
                                DataItem[] refItemList = bu.GetItems(refItemType, null, null, 0, 0, ref count);
                                dropdown.DataSource = refItemList;
                                if (itemDetail != null)
                                {
                                    dropdown.SelectedValue = itemDetail[schema.Column].ToString();
                                }
                            }
                        }
                        else if (schema.Data.StartsWith("item:"))
                        {
                            string refString = schema.Data.Replace("item:", string.Empty);
                            string[] refItemStrings = refString.Split('|');
                            foreach (string refItemString in refItemStrings)
                            {
                                //refItemString = "1:Girl"
                                string[] refItem = refItemString.Split(':');
                                dropdown.Items.Add(new System.Web.UI.WebControls.ListItem(refItem[1], refItem[0]));
                            }
                            if (itemDetail != null)
                            {
                                dropdown.SelectedValue = itemDetail[schema.Column].ToString();
                            }
                        }

                        Controls.Add(dropdown);
                        break;
                    case GenericBusiness.ControlType.ListBox:
                        ListBox listBox = new ListBox()
                        {
                            ID = schema.InputControl + schema.Column,
                        };
                        if (schema.Data.StartsWith("ref:"))
                        {
                            string refItemName = schema.Data.Replace("ref:", string.Empty);
                            GenericBusiness.ItemType refItemType = GenericBusiness.ItemType.LoadType(refItemName);
                            if (refItemType != null)
                            {
                                listBox.DataValueField = refItemType.KeyField;
                                listBox.DataTextField = refItemType.DisplayField;
                                int count = 0;
                                DataItem[] refItemList = bu.GetItems(refItemType, null, null, 0, 0, ref count);
                                listBox.DataSource = refItemList;
                                if (itemDetail != null)
                                {
                                    listBox.SelectedValue = itemDetail[schema.Column].ToString();
                                }
                            }
                        }
                        else if (schema.Data.StartsWith("item:"))
                        {
                            string refString = schema.Data.Replace("item:", string.Empty);
                            string[] refItemStrings = refString.Split('|');
                            List<DataItem> refItemList = new List<DataItem>();
                            foreach (string refItemString in refItemStrings)
                            {
                                //refItemString = "1:Girl"
                                string[] refItem = refItemString.Split(':');
                                DataItem item = new DataItem();
                                item["key"] = refItem[0];
                                item["value"] = refItem[1];
                                refItemList.Add(item);
                            }
                            listBox.DataValueField = "key";
                            listBox.DataTextField = "value";
                            listBox.DataSource = refItemList;
                            if (itemDetail != null)
                            {
                                listBox.SelectedValue = itemDetail[schema.Column].ToString();
                            }
                        }

                        Controls.Add(listBox);
                        break;
                    case GenericBusiness.ControlType.RadioButtonList:
                        RadioButtonList radioBtnList = new RadioButtonList() { 
                            ID = schema.InputControl + schema.Column, 
                            TextAlign = System.Web.UI.WebControls.TextAlign.Left, 
                            RepeatDirection = System.Web.UI.WebControls.RepeatDirection.Horizontal};
                        if(schema.Data.StartsWith("ref:"))
                        {
                            string refItemName = schema.Data.Replace("ref:", string.Empty);
                            GenericBusiness.ItemType refItemType = GenericBusiness.ItemType.LoadType(refItemName);
                            if (refItemType != null)
                            {
                                radioBtnList.DataValueField = refItemType.KeyField;
                                radioBtnList.DataTextField = refItemType.DisplayField;
                                int count = 0;
                                DataItem[] refItemList = bu.GetItems(refItemType, null, null, 0, 0, ref count);
                                radioBtnList.DataSource = refItemList;
                                if (itemDetail != null)
                                {
                                    radioBtnList.SelectedValue = itemDetail[schema.Column].ToString();
                                }
                            }
                        }
                        else if (schema.Data.StartsWith("item:"))
                        {
                            string refString = schema.Data.Replace("item:", string.Empty);
                            string[] refItemStrings = refString.Split('|');
                            List<DataItem> refItemList = new List<DataItem>();
                            foreach (string refItemString in refItemStrings)
                            {
                                //refItemString = "1:Girl"
                                string[] refItem = refItemString.Split(':');
                                DataItem item = new DataItem();
                                item["key"] = refItem[0];
                                item["value"] = refItem[1];
                                refItemList.Add(item);
                            }
                            radioBtnList.DataValueField = "key";
                            radioBtnList.DataTextField = "value";
                            radioBtnList.DataSource = refItemList;
                            if (itemDetail != null)
                            {
                                radioBtnList.SelectedValue = itemDetail[schema.Column].ToString();
                            }
                        }

                        Controls.Add(radioBtnList);
                        break;
                    case GenericBusiness.ControlType.TextArea:
                        Controls.Add(new TextBox() { 
                            ID = schema.InputControl + schema.Column, 
                            Text = itemDetail != null ? itemDetail[schema.Column].ToString() : string.Empty, 
                            TextMode = System.Web.UI.WebControls.TextBoxMode.MultiLine });
                        break;
                    case GenericBusiness.ControlType.TextBox:
                        Controls.Add(new TextBox() { 
                            ID = schema.InputControl + schema.Column, 
                            Text = itemDetail != null ? itemDetail[schema.Column].ToString() : string.Empty });
                        break;
                    default:
                        break;

                }
            }
        }

        public override void RenderControl(HtmlTextWriter writer)
        {
            int controlCount = Controls.Count - 1;
            writer.RenderBeginTag(HtmlTextWriterTag.Table);            
            for (int i = 0; i < controlCount; i += 2)
            {
                // Render a pair of label-control in a table row
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                Controls[i].RenderControl(writer);
                writer.RenderEndTag();    // td
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                Controls[i + 1].RenderControl(writer);
                writer.RenderEndTag();    // td
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.RenderEndTag();    // tr
            }
            writer.RenderEndTag();    // table
        }
    }
}
